<?php
namespace backend\controllers;

use Yii;
use backend\controllers\BaseController;
use backend\models\friend\User;
use backend\models\friend\Friend;
use yii\data\Pagination;
use common\components\CreateExcel;
use Weixin\Dialog\DataCube;

/**
 * 用户关系功能模块
 * @author 徐焕亭
 */
class FriendController extends BaseController
{
	public $enableCsrfValidation = false;
    
    /**
     * @inheritdoc  用户关系管理
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * 微信粉丝管理
     */
    public function actionFans()
    {
        /*$result = DataCube::getDataCube('getusercumulate', '2016-01-04', '2016-01-07');
        if (! $result) {
            var_dump(DataCube::getError());
        }
        var_dump($result);*/
		return $this->goBack();
    }

	 /**
     * @inheritdoc  搜索用户
     */
    public function actionSearch()
    {
		$request = Yii::$app->request;
		if(!empty($request->get('page'))){
			$this->session()->get('nickname');
		}else{
			$nickname = $request->post('nickname');

			$this->session()->set('nickname', $nickname);
		}	
        $user = new User();
		$data = $user->searchUser($nickname);
        if ($data == 1) {
            $this->error('用户不存在！', ['friend/index']);
        } elseif($data == 2) {
            $this->error('此用户暂无好友！', ['friend/index']);
        } else {
            $model = User::find();
            $pagination = new Pagination([
                'defaultPageSize' => 3,
                'totalCount' => Friend::find()->where(['user_id'=>$user_id])->count(),
            ]);

            $model = $model->where($data['cond'])
                ->offset($pagination->offset)
                ->limit($pagination->limit)
                ->asarray()->all();
            return $this->render('index', [
                'model' => $model,
                'pagination' => $pagination,
                'user'=>$data['re'],
                'user_name'=>$nickname,
            ]);
        }
        
		
	}
	/**	
	*	导出搜索结果（下载Excel表格）
	*/
	public function actionDownload(){
        //查询结果
		$request = Yii::$app->request;
		$nickname = $request->get('nickname','');
		$model = new User();
		if (!$data = $model->downloadSel($nickname)){
            $this->error('您要导出的数据不存在！', ['friend/index']);
        }

        //生成excel
        $excel = new CreateExcel();
        $excel->createByArray($data,'好友搜索结果列表',['好友ID','好友姓名','添加时间']);
	}
}